package com.gpnu7_412.yanzhi.controller.user;

import com.gpnu7_412.yanzhi.entity.User;
import com.gpnu7_412.yanzhi.exception.custom.RequestDataException;
import com.gpnu7_412.yanzhi.service.UserService;
import com.gpnu7_412.yanzhi.status.Impl.ResultCode;
import com.gpnu7_412.yanzhi.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 用户注册控制器
 * @author ZZH
 */
@CrossOrigin
@RestController
@RequestMapping ("/user")
public class RegisterController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 用户注册
     * @param requestMap 请求数据，需包含：userName 用户名，email 用户邮箱，password 用户密码
     * @return 响应数据
     */
    @PostMapping("/register")
    public Result register(@RequestBody Map<String, Object> requestMap) {
        // 获取信息
        User user = new User();
        user.setUserName((String) requestMap.get("userName"));
        user.setEmail((String) requestMap.get("email"));
        user.setPassword((String) requestMap.get("password"));
        user.setAvatar("default.jpg");
        user.setPermission("用户");
        String verification = (String) requestMap.get("verification");
        // 尝试从 Redis 中取出验证码
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        String storeCode = operations.get(user.getEmail());
        // 验证码校验
        if (storeCode == null || !storeCode.equals(verification)) {
            return new Result(ResultCode.FAILED, "验证码错误");
        }
        // 用户注册
        if (!userService.register(user)) {
            throw new RequestDataException("参数为空");
        }
        return new Result(ResultCode.SUCCESS, "注册成功");
    }
}
